/*
 Copyright (c) 2010, Advanced Micro Devices
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without modification, are permitted 
 provided that the following conditions are met:
 
 Redistributions of source code must retain the above copyright notice, this list of conditions 
 and the following disclaimer.
 
 Redistributions in binary form must reproduce the above copyright notice, this list of 
 conditions and the following disclaimer in the documentation and/or other materials provided 
 with the distribution.
 
 Neither the name of Advanced Micro Devices nor the names of its contributors may be used to endorse 
 or promote products derived from this software without specific prior written permission.
 
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR 
 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
 AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR 
 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
 OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
 POSSIBILITY OF SUCH DAMAGE.
 */

#include <QtGui>
#include <QDebug>

#include <iostream>
#include <fstream>

#include <sstream>

#include "editorwindow.h"
#include "EditorView.h"
//#include "propertiesdialog.h"
#include "edgePropertiesDialog.h"

EditorWindow::EditorWindow()
{
	allocateGraphicsSurface();
    mScene = new QGraphicsScene( 0, 0, width, height );

    mView = new EditorView;
    mView->setScene(mScene);
    mView->setDragMode(QGraphicsView::RubberBandDrag);
    mView->setRenderHints(QPainter::Antialiasing
                         | QPainter::TextAntialiasing);
    mView->setContextMenuPolicy(Qt::ActionsContextMenu);
	
    minZ = 0;
    maxZ = 0;
    seqNumber = 0;
	tree = NULL;

    setCentralWidget(mView);
	mDockWidget = new QDockWidget( tr( "Objects" ), this);
	mDockWidget->setAllowedAreas(Qt::LeftDockWidgetArea |
								Qt::RightDockWidgetArea);
	mDockWidget->setWidget( tree );
	addDockWidget(Qt::LeftDockWidgetArea, mDockWidget);
	
    createActions();
    createMenus();
    createToolBars();
	createTree();

    connect(mScene, SIGNAL(selectionChanged()),
            this, SLOT(updateActions()));

    setWindowTitle(tr("PipelineKit"));
    updateActions();
}


void EditorWindow::allocateGraphicsSurface()
{
	width = 1000;
	height = 1000;
	//to do iterate over all objects in the layout
}


#if 0
void EditorWindow::addNode()
{
    Node *node = new Node;
    node->setText(tr("Node %1").arg(seqNumber + 1));
    setupNode(node);
}
#endif

void EditorWindow::addLink()
{
    NodePair nodes = selectedNodePair();
    if (nodes == NodePair())
        return;

	Node * fromNode = nodes.first;
	Node * toNode = nodes.second;

	if( fromNode->typeOf() != "Stage" || toNode->typeOf() != "Stage" ){
		return;
	}

	Edge edge;
	edge.fromNode = fromNode;
	edge.toNode = toNode;
	EdgePropertiesDialog dialog( &edge, view() );
	dialog.exec();
	fromNode = edge.fromNode;
	toNode = edge.toNode;
	
	Link *link = new Link(nodes.first, nodes.second);
    mScene->addItem(link);

	Graph * fromGraph = fromNode->graph();
	Graph * toGraph = toNode->graph();

	if( fromGraph == NULL && toGraph == NULL ){
		addGraph( fromNode, toNode );
		createTree();
	}
	else if( fromGraph == NULL && toGraph != NULL ){
		toGraph->edgeIs( fromNode, toNode );
		fromNode->graphIs( toGraph );
		toGraph->vertexIs( fromNode );
		toGraph->startVertexIs( fromNode );
	}
	else if( toGraph == NULL && fromGraph != NULL ){
		fromGraph->edgeIs( fromNode, toNode );
		toNode->graphIs( fromGraph );
		fromGraph->vertexIs( toNode );
	}
	else{
		fromGraph->edgeIs( fromNode, toNode );
		if( fromGraph != toGraph ){
			coalesceGraphs( fromGraph, toGraph );
			createTree();
		}
	}
}

void EditorWindow::addBuffer()
{
	Buffer * buffer = new Buffer( mView, this );
	setupNode( buffer );
	buffer->propertiesDialog();
	buffer->formatText();
	mBuffers.insert( buffer->name(), buffer );
	createTree();
}

void EditorWindow::addStage()
{
	Stage * stage = new Stage( mView, this );
	setupNode( stage );
	stage->propertiesDialog();
	stage->formatText();
	mStages.insert( stage->name(), stage );
	createTree();
}

void EditorWindow::addKernel()
{
	Kernel * kernel = new Kernel( mView, this );
	setupNode( kernel );
	kernel->propertiesDialog();
	kernel->formatText();
	mKernels.insert( kernel->name(), kernel );
	createTree();
}

void EditorWindow::addUniform()
{
	Uniform * uniform = new Uniform( mView, this );
	setupNode( uniform );
	uniform->propertiesDialog();
	uniform->formatText();
	mUniforms.insert( uniform->name(), uniform );
	createTree();
}

void EditorWindow::addEquation()
{
	Equation * equation = new Equation( mView, this );
	setupNode( equation );
	equation->propertiesDialog();
	equation->formatText();
	mEquations.insert( equation->name(), equation );
	createTree();
}

QString EditorWindow::newGraphName()
{
	QString controlGraphName;
	Graphs::iterator gIt;
	int idx = 0;
	do{
		std::stringstream o;
		o << idx++;
		std::string s = o.str();
		controlGraphName = "g" + QString( s.c_str() ) + "_control";
		gIt = controlGraphs().find( controlGraphName );
	}while( gIt != controlGraphs().end() );
	return controlGraphName;
}

void EditorWindow::addGraph( Node * fromNode, Node * toNode )
{
	Graph * controlGraph = new Graph( mView, this );
	controlGraph->nameIs( newGraphName() );
#if 0
	qDebug() << "addGraph " << controlGraph->name()
		<< " = " << fromNode->name() << ", "
		<< toNode->name();
#endif
	controlGraph->edgeIs( fromNode, toNode );
	controlGraph->vertexIs( fromNode );
	controlGraph->vertexIs( toNode );
	controlGraph->startVertexIs( fromNode );
	mControlGraphs.insert( controlGraph->name(), controlGraph );
	fromNode->graphIs( controlGraph );
	toNode->graphIs( controlGraph );
	// dataflow graph
	//to do dataflow graph
	createTree();
}

void EditorWindow::deleteGraphEdge( Link * link )
{
	Node * fromNode = link->fromNode();
	Node * toNode = link->toNode();
	if( fromNode == NULL || toNode == NULL ){
		return;
	}
	if( fromNode->typeOf() != "Stage" || toNode->typeOf() != "Stage" ){
		return;
	}
	Graph * graph = fromNode->graph();
	graph->deleteEdge( fromNode, toNode );
	graph->deleteVertex( toNode );

	Graph * newGraph = new Graph( mView, this );
	newGraph->nameIs( newGraphName() );
	mControlGraphs.insert( newGraph->name(), newGraph );

	Vertices newVertices;
	newVertices.insert( toNode );
	while( newVertices.size() ){
		Edge edge;
		Vertices::iterator vIt = newVertices.begin();
		Node * newVertex = *vIt;
		newVertices.remove( newVertex );
		do{
			edge = graph->findEdgeContaining( newVertex );
			if( edge.fromNode != NULL ){
				newGraph->edgeIs( edge.fromNode, edge.toNode );
				graph->deleteEdge( edge.fromNode, edge.toNode );
				if( !newVertices.contains( edge.fromNode )){
					newVertices.insert( edge.fromNode );
				}
				if( !newVertices.contains( edge.toNode )){
					newVertices.insert( edge.toNode );
				}
			}
		}while( edge.fromNode != NULL );
		graph->deleteVertex( newVertex );
	}//while
	if( graph->vertices().size() == 0 ){
		mControlGraphs.remove( graph->name() );
		delete graph;
	}
}


void EditorWindow::del()
{
    QList<QGraphicsItem *> items = mScene->selectedItems();

	// remove selected links before deleting selected items
    QMutableListIterator<QGraphicsItem *> i(items);
    while (i.hasNext()) {
        Link *link = dynamic_cast<Link *>(i.next());
        if (link) {
			deleteGraphEdge( link );
            delete link;
            i.remove();
        }
    }//while

    qDeleteAll(items);
	createTree();
}

void EditorWindow::cut()
{
    Node *node = selectedNode();
    if (!node)
        return;

    copy();
    delete node;
}

void EditorWindow::copy()
{
    Node *node = selectedNode();
    if (!node)
        return;

    QString str = QString("Node %1 %2 %3 %4")
                  .arg(node->textColor().name())
                  .arg(node->outlineColor().name())
                  .arg(node->backgroundColor().name())
                  .arg(node->text());
    QApplication::clipboard()->setText(str);
}

void EditorWindow::paste()
{
    QString str = QApplication::clipboard()->text();
    QStringList parts = str.split(" ");

#if 0
    if (parts.count() >= 5 && parts.first() == "Node") {
        Node *node = new Node;
        node->setText(QStringList(parts.mid(4)).join(" "));
        node->setTextColor(QColor(parts[1]));
        node->setOutlineColor(QColor(parts[2]));
        node->setBackgroundColor(QColor(parts[3]));
        setupNode(node);
    }
#else
    if (parts.count() >= 5 && parts.first() == "Buffer") {
        Buffer *buffer = new Buffer( mView, this );
        buffer->setText(QStringList(parts.mid(4)).join(" "));
        buffer->setTextColor(QColor(parts[1]));
        buffer->setOutlineColor(QColor(parts[2]));
        buffer->setBackgroundColor(QColor(parts[3]));
        setupNode(buffer);
    }
    if (parts.count() >= 5 && parts.first() == "Stage") {
        Stage *stage = new Stage( mView, this );
        stage->setText(QStringList(parts.mid(4)).join(" "));
        stage->setTextColor(QColor(parts[1]));
        stage->setOutlineColor(QColor(parts[2]));
        stage->setBackgroundColor(QColor(parts[3]));
        setupNode(stage);
    }
	
#endif
}

void EditorWindow::bringToFront()
{
    ++maxZ;
    setZValue(maxZ);
}

void EditorWindow::sendToBack()
{
    --minZ;
    setZValue(minZ);
}

void EditorWindow::properties()
{
    Node *node = selectedNode();
    Link *link = selectedLink();

    if (node) {
#if 0
        PropertiesDialog dialog(node, this);
        dialog.exec();
#else
		node->propertiesDialog();
#endif
    } else if (link) {
#if 0
        QColor color = QColorDialog::getColor(link->color(), this);
        if (color.isValid())
            link->setColor(color);
#endif
    }
}

void EditorWindow::updateActions()
{
    bool hasSelection = !mScene->selectedItems().isEmpty();
    bool isNode = (selectedNode() != 0);
    bool isNodePair = (selectedNodePair() != NodePair());

    cutAction->setEnabled(isNode);
    copyAction->setEnabled(isNode);
    addLinkAction->setEnabled(isNodePair);
    deleteAction->setEnabled(hasSelection);
    bringToFrontAction->setEnabled(isNode);
    sendToBackAction->setEnabled(isNode);
    propertiesAction->setEnabled(isNode);

    foreach (QAction *action, mView->actions())
        mView->removeAction(action);

    foreach (QAction *action, editMenu->actions()) {
        if (action->isEnabled())
            mView->addAction(action);
    }
}

void EditorWindow::createActions()
{
    exitAction = new QAction(tr("E&xit"), this);
    exitAction->setShortcut(tr("Ctrl+Q"));
    connect(exitAction, SIGNAL(triggered()), this, SLOT(close()));

#if 0
    addNodeAction = new QAction(tr("Add &Node"), this);
    addNodeAction->setIcon(QIcon(":/images/node.png"));
    addNodeAction->setShortcut(tr("Ctrl+N"));
    connect(addNodeAction, SIGNAL(triggered()), this, SLOT(addNode()));
#endif
	
    addLinkAction = new QAction(tr("Add &Link"), this);
    addLinkAction->setIcon(QIcon(":/images/link.png"));
    addLinkAction->setShortcut(tr("Ctrl+L"));
    connect(addLinkAction, SIGNAL(triggered()), this, SLOT(addLink()));

    deleteAction = new QAction(tr("&Delete"), this);
    deleteAction->setIcon(QIcon(":/images/delete.png"));
    deleteAction->setShortcut(tr("Del"));
    connect(deleteAction, SIGNAL(triggered()), this, SLOT(del()));

    cutAction = new QAction(tr("Cu&t"), this);
    cutAction->setIcon(QIcon(":/images/cut.png"));
    cutAction->setShortcut(tr("Ctrl+X"));
    connect(cutAction, SIGNAL(triggered()), this, SLOT(cut()));

    copyAction = new QAction(tr("&Copy"), this);
    copyAction->setIcon(QIcon(":/images/copy.png"));
    copyAction->setShortcut(tr("Ctrl+C"));
    connect(copyAction, SIGNAL(triggered()), this, SLOT(copy()));

    pasteAction = new QAction(tr("&Paste"), this);
    pasteAction->setIcon(QIcon(":/images/paste.png"));
    pasteAction->setShortcut(tr("Ctrl+V"));
    connect(pasteAction, SIGNAL(triggered()), this, SLOT(paste()));

    bringToFrontAction = new QAction(tr("Bring to &Front"), this);
    bringToFrontAction->setIcon(QIcon(":/images/bringtofront.png"));
    connect(bringToFrontAction, SIGNAL(triggered()),
            this, SLOT(bringToFront()));

    sendToBackAction = new QAction(tr("&Send to Back"), this);
    sendToBackAction->setIcon(QIcon(":/images/sendtoback.png"));
    connect(sendToBackAction, SIGNAL(triggered()),
            this, SLOT(sendToBack()));

    propertiesAction = new QAction(tr("P&roperties..."), this);
    connect(propertiesAction, SIGNAL(triggered()),
            this, SLOT(properties()));
	
	newAction = new QAction( tr( "&New" ), this );
	newAction->setShortcut( tr( "Ctrl+N" ));
	connect( newAction, SIGNAL( triggered() ), this, SLOT( new_() ));
	
	openAction = new QAction( tr( "&Open..." ), this );
	openAction->setShortcut( tr( "Ctrl+O" ));
	connect( openAction, SIGNAL( triggered() ), this, SLOT( open() ));
	
	importAction = new QAction( tr( "&Import..." ), this );
	importAction->setShortcut( tr( "Ctrl+I" ));
	//connect...
	
	closeAction = new QAction( tr( "C&lose" ), this );
	closeAction->setShortcut( tr( "Ctrl+l" ));
	//connect...
	
	saveAction = new QAction( tr( "&Save" ), this );
	saveAction->setShortcut( tr( "Ctrl+S" ));
	connect( saveAction, SIGNAL( triggered() ), this, SLOT( save() ));
	
	saveAsAction = new QAction( tr( "Save &As..." ), this );
	saveAsAction->setShortcut( tr( "Ctrl+A" ));
	connect( saveAsAction, SIGNAL( triggered() ), this, SLOT( saveAs() ));
	
	layoutAction = new QAction( tr( "La&yout" ), this );
	layoutAction->setShortcut( tr( "Ctrl+y" ));
	
	bufferAction = new QAction( tr( "&Buffer" ), this );
	bufferAction->setShortcut( tr( "Ctrl+B" ));
	connect( bufferAction, SIGNAL( triggered() ), this, SLOT( addBuffer() ));
	
	stageAction = new QAction( tr( "S&tage" ), this );
	stageAction->setShortcut( tr( "Ctrl+t" ));
	connect( stageAction, SIGNAL( triggered() ), this, SLOT( addStage() ));
	
	kernelAction = new QAction( tr( "&Kernel" ), this );
	kernelAction->setShortcut( tr( "Ctrl+K" ));
	connect( kernelAction, SIGNAL( triggered() ), this, SLOT( addKernel() ));
	
	uniformAction = new QAction( tr( "&Uniform" ), this );
	uniformAction->setShortcut( tr( "Ctrl+U" ));
	connect( uniformAction, SIGNAL( triggered() ), this, SLOT( addUniform() ));
	
	equationAction = new QAction( tr( "Inva&riant" ), this );
	equationAction->setShortcut( tr( "Ctrl+r" ));
	connect( equationAction, SIGNAL( triggered() ), this, SLOT( addEquation() ));
	
	buildAction = new QAction( tr( "Bui&ld" ), this );
	buildAction->setShortcut( tr( "Ctrl+l" ));
	connect( buildAction, SIGNAL( triggered() ), this, SLOT( buildProgram() ));
}

void EditorWindow::createMenus()
{
    fileMenu = menuBar()->addMenu(tr("&File"));
	fileMenu->addAction( newAction );
	fileMenu->addAction( openAction );
	fileMenu->addAction( importAction );
	//fileMenu->addAction( closeAction );//crashes BAD_ACCESS
	fileMenu->addAction( saveAction );
	fileMenu->addAction( saveAsAction );
    fileMenu->addAction(exitAction);

    editMenu = menuBar()->addMenu(tr("&Edit"));
#if 0
    editMenu->addAction(addNodeAction);
#endif
    editMenu->addAction(addLinkAction);
    editMenu->addAction(deleteAction);
    editMenu->addSeparator();
	editMenu->addAction( layoutAction );
	editMenu->addSeparator();
    editMenu->addAction(cutAction);
    editMenu->addAction(copyAction);
    editMenu->addAction(pasteAction);
    editMenu->addSeparator();
    editMenu->addAction(bringToFrontAction);
    editMenu->addAction(sendToBackAction);
    editMenu->addSeparator();
    editMenu->addAction(propertiesAction);
	
	insertMenu = menuBar()->addMenu( tr( "&Insert" ));
	insertMenu->addAction( bufferAction );
	insertMenu->addAction( kernelAction );
	insertMenu->addAction( stageAction );
	insertMenu->addAction( uniformAction );
	insertMenu->addAction( equationAction );

	buildMenu = menuBar()->addMenu( tr( "Bui&ld" ));
	buildMenu->addAction( buildAction );
}

void EditorWindow::createToolBars()
{
    editToolBar = addToolBar(tr("Edit"));
#if 0
    editToolBar->addAction(addNodeAction);
#else
	editToolBar->addAction( uniformAction );
	editToolBar->addAction( equationAction );
	editToolBar->addAction( bufferAction );
	editToolBar->addAction( kernelAction );
	editToolBar->addAction( stageAction );
#endif
    editToolBar->addAction(addLinkAction);
    editToolBar->addAction(deleteAction);
    editToolBar->addSeparator();
    editToolBar->addAction(cutAction);
    editToolBar->addAction(copyAction);
    editToolBar->addAction(pasteAction);
    editToolBar->addSeparator();
    editToolBar->addAction(bringToFrontAction);
    editToolBar->addAction(sendToBackAction);
}

void EditorWindow::selectObjectFromTree( QTreeWidgetItem * item, int column )
{
	Uniforms::iterator unIt = uniforms().find( item->text( column ));
	if( unIt != uniforms().end() ){
		Uniform * uniform = unIt.value();
		uniform->setSelected( true );
		return;
	}

	Equations::iterator eqIt = equations().find( item->text( column ));
	if( eqIt != equations().end() ){
		Equation * equation = eqIt.value();
		equation->setSelected( true );
		return;
	}

	Buffers::iterator bIt = buffers().find( item->text( column) );
	if( bIt != buffers().end() ){
		Buffer * buffer = bIt.value();
		buffer->setSelected( true );
		return;
	}

	Kernels::iterator kIt = kernels().find( item->text( column ));
	if( kIt != kernels().end() ){
		Kernel * kernel = kIt.value();
		kernel->setSelected( true );
		return;
	}

	Stages::iterator sIt = stages().find( item->text( column ));
	if( sIt != stages().end() ){
		Stage * stage = sIt.value();
		stage->setSelected( true );
		return;
	}

	Graphs::iterator gIt = controlGraphs().find( item->text( column ));
	if( gIt != controlGraphs().end() ){
		Graph * graph = gIt.value();
		graph->setSelected( true );
		return;
	}
}

void EditorWindow::displayPropertiesFromTree( QTreeWidgetItem * item, int column )
{
	Uniforms::iterator unIt = uniforms().find( item->text( column ));
	if( unIt != uniforms().end() ){
		Uniform * uniform = unIt.value();
		uniform->propertiesDialog();
		return;
	}

	Equations::iterator eqIt = equations().find( item->text( column ));
	if( eqIt != equations().end() ){
		Equation * equation = eqIt.value();
		equation->propertiesDialog();
		return;
	}

	Buffers::iterator bIt = buffers().find( item->text( column) );
	if( bIt != buffers().end() ){
		Buffer * buffer = bIt.value();
		buffer->propertiesDialog();
		return;
	}

	Kernels::iterator kIt = kernels().find( item->text( column ));
	if( kIt != kernels().end() ){
		Kernel * kernel = kIt.value();
		kernel->propertiesDialog();
		return;
	}

	Stages::iterator sIt = stages().find( item->text( column ));
	if( sIt != stages().end() ){
		Stage * stage = sIt.value();
		stage->propertiesDialog();
		return;
	}

	Graphs::iterator gIt = controlGraphs().find( item->text( column ));
	if( gIt != controlGraphs().end() ){
		Graph * graph = gIt.value();
		graph->propertiesDialog();
		return;
	}
}

void EditorWindow::createTree()
{
	QTreeWidget * oldTree = tree;
	tree = new QTreeWidget();
	tree->setColumnCount( 1 );
	tree->setSortingEnabled( false );
	QList<QTreeWidgetItem *> items;
	connect( tree, SIGNAL( itemDoubleClicked( QTreeWidgetItem *, int ) ), 
		this, SLOT( displayPropertiesFromTree( QTreeWidgetItem *, int ) ));
	connect( tree, SIGNAL( itemClicked( QTreeWidgetItem *, int ) ), 
		this, SLOT( selectObjectFromTree( QTreeWidgetItem *, int ) ));
	
	QTreeWidgetItem * uniformsItem = new QTreeWidgetItem( tree, QStringList( QString( "Uniforms" )));
	for( Uniforms::iterator uIt = mUniforms.begin(); uIt != mUniforms.end(); uIt++ ){
		Uniform * uniform = uIt.value();
		QTreeWidgetItem * childItem = new QTreeWidgetItem( uniformsItem, QStringList( uniform->name() ));
		uniformsItem->addChild( childItem );
	}//for
	items.push_back( uniformsItem );
	
	QTreeWidgetItem * equationsItem = new QTreeWidgetItem( tree, QStringList( QString( "Invariants" )));
	for( Equations::iterator eIt = mEquations.begin(); eIt != mEquations.end(); eIt++ ){
		Equation * equation = eIt.value();
		QTreeWidgetItem * childItem = new QTreeWidgetItem( equationsItem, QStringList( equation->name() ));
		equationsItem->addChild( childItem );
	}//for
	items.push_back( equationsItem );
	
	QTreeWidgetItem * buffersItem = new QTreeWidgetItem( tree, QStringList( QString( "Buffers" )));
	for( Buffers::iterator bIt = mBuffers.begin(); bIt != mBuffers.end(); bIt++ ){
		Buffer * buffer = bIt.value();
		QTreeWidgetItem * childItem = new QTreeWidgetItem( buffersItem, QStringList( buffer->name() ));
		buffersItem->addChild( childItem );
	}//for
	items.push_back( buffersItem );
	
	QTreeWidgetItem * kernelsItem = new QTreeWidgetItem( tree, QStringList( QString( "Kernels" )));
	for( Kernels::iterator kIt = mKernels.begin(); kIt != mKernels.end(); kIt++ ){
		Kernel * kernel = kIt.value();
		QTreeWidgetItem * childItem = new QTreeWidgetItem( kernelsItem, QStringList( kernel->name() ));
		kernelsItem->addChild( childItem );
	}//for
	items.push_back( kernelsItem );
	
	QTreeWidgetItem * stagesItem = new QTreeWidgetItem( tree, QStringList( QString( "Stages" )));
	for( Stages::iterator sIt = mStages.begin(); sIt != mStages.end(); sIt++ ){
		Stage * stage = sIt.value();
		QTreeWidgetItem * childItem = new QTreeWidgetItem( stagesItem, QStringList( stage->name() ));
		stagesItem->addChild( childItem );
	}//for
	items.push_back( stagesItem );
	
	QTreeWidgetItem * graphsItem = new QTreeWidgetItem( tree, QStringList( QString( "Graphs" )));
	for( Graphs::iterator gIt = mControlGraphs.begin(); gIt != mControlGraphs.end(); gIt++ ){
		Graph * graph = gIt.value();
		QTreeWidgetItem * childItem = new QTreeWidgetItem( graphsItem, QStringList( graph->name() ));
		graphsItem->addChild( childItem );
	}//for
	items.push_back( graphsItem );
	
	tree->insertTopLevelItems(0, items);
	tree->setHeaderLabel( currentFileName() );
	
#if 1
	// pass over oldTree, set matching selections in new tree
	if( oldTree != NULL ){
		for( int i = 0; i < tree->topLevelItemCount(); ++i ){
			QTreeWidgetItem * item = tree->topLevelItem( i );
			QTreeWidgetItem * oldItem = oldTree->topLevelItem( i );
			if( oldItem->isExpanded() ){
				item->setExpanded( true );
			}
		}//for
	}
#endif
	delete oldTree;
	
	mDockWidget->setWidget( tree );

}

void EditorWindow::setZValue(int z)
{
    Node *node = selectedNode();
    if (node)
        node->setZValue(z);
}

void EditorWindow::setupNode(Node *node)
{
    node->setPos(QPoint(80 + (100 * (seqNumber % 5)),
                        80 + (50 * ((seqNumber / 5) % 7))));
    mScene->addItem(node);
    ++seqNumber;

    mScene->clearSelection();
    node->setSelected(true);
    bringToFront();
}


Node *EditorWindow::selectedNode() const
{
    QList<QGraphicsItem *> items = mScene->selectedItems();
    if (items.count() == 1) {
        return dynamic_cast<Node *>(items.first());
    } else {
        return 0;
    }
}

Link *EditorWindow::selectedLink() const
{
    QList<QGraphicsItem *> items = mScene->selectedItems();
    if (items.count() == 1) {
        return dynamic_cast<Link *>(items.first());
    } else {
        return 0;
    }
}

EditorWindow::NodePair EditorWindow::selectedNodePair() const
{
    QList<QGraphicsItem *> items = mScene->selectedItems();
    if (items.count() == 2) {
        Node *first = dynamic_cast<Node *>(items.first());
        Node *second = dynamic_cast<Node *>(items.last());
		if (first && second){
#if 0
			qDebug() << "selected node pair " << first->name()
				<< ", " << second->name();
#endif
            return NodePair(first, second);
		}
    }
    return NodePair();
}

void EditorWindow::saveAs()
{
	QFileDialog dialog( this );
	dialog.setFileMode( QFileDialog::AnyFile );
	dialog.setNameFilter( tr( "Pipelines (*.ppl);;All files (*.*)" ));
	dialog.setViewMode( QFileDialog::List );
	if ( dialog.exec() ){
		QStringList fileNames = dialog.selectedFiles();
		currentFileNameIs( fileNames[ 0 ] );
		save();
	}
}

void EditorWindow::save()
{
	if( currentFileName().compare( "" ) == 0 ){
		saveAs();
	}
	else{
		QFile file( currentFileName() );
		if( !file.open( QFile::WriteOnly | QFile::Text )){
			// to do issue an error
			return;
		}
		QXmlStreamWriter xmlsw( &file );
		xmlsw.setAutoFormatting( true );
		xmlsw.writeStartDocument();
		xmlsw.writeStartElement( "pipeline" );
		foreach( Uniform * uniform, uniforms() ){
			uniform->writeXml( xmlsw );
		}//foreach
		foreach( Equation * equation, equations() ){
			equation->writeXml( xmlsw );
		}//foreach
		foreach( Buffer * buffer, buffers() ){
			buffer->writeXml( xmlsw );
		}//foreach
		foreach( Kernel * kernel, kernels() ){
			kernel->writeXml( xmlsw );
		}//foreach
		foreach( Stage * stage, stages() ){
			stage->writeXml( xmlsw );
		}//foreach
		foreach( Graph * graph, controlGraphs() ){
			graph->writeXml( xmlsw );
		}
		xmlsw.writeEndDocument();
	}
}

void EditorWindow::saveObjects()
{
	mControlGraphs_ = mControlGraphs;
	mStages_ = mStages;
	mKernels_ = mKernels;
	mEquations_ = mEquations;
	mUniforms_ = mUniforms;
}

void EditorWindow::restoreObjects()
{
	mControlGraphs = mControlGraphs_;
	mStages = mStages_;
	mKernels = mKernels_;
	mEquations = mEquations_;
	mUniforms = mUniforms_;
}

void EditorWindow::clearObjects()
{
	mControlGraphs.clear();
	mStages.clear();
	mKernels.clear();
	mEquations.clear();
	mUniforms.clear();
}

void EditorWindow::restoreGraphs()
{
	foreach( Graph * graph, mControlGraphs ){
		foreach( Node * vertex, graph->vertices() ){
			vertex->graphIs( graph );
		}//foreach
	}//foreach
}

void EditorWindow::new_()
{
	EditorWindowContainer * editorWindowContainer = new EditorWindowContainer();
	editorWindowContainer->start();
}

void EditorWindow::initializeOneNew( QString lhsName, QString dataType, QString rhs)
{
	Uniform * uniform = new Uniform( mView, this );
	setupNode( uniform );
	uniform->nameIs( lhsName );
	uniform->dataTypeIs( dataType );
	uniform->formatText();
	uniforms().insert( lhsName, uniform );

	Equation * equation = new Equation( mView, this );
	setupNode( equation );
	equation->lhsNameIs( lhsName );
	equation->rhsIs( rhs );
	equation->formatText();
	equations().insert( equation->name(), equation );
}

void EditorWindow::initializeNew()//this function is called from the EditorViewContainer constructor
{
	initializeOneNew( "globalDimensions", "int", "1" );
	initializeOneNew( "globalRange", "string", "NDRange( undefined )" );
	initializeOneNew( "localDimensions", "int", "1" );
	initializeOneNew( "localRange", "string", "NDRange( undefined )" );
	createTree();
}

void EditorWindow::open()
{
	QFileDialog dialog( this );
	dialog.setFileMode( QFileDialog::ExistingFile );
	dialog.setNameFilter( tr( "Pipelines (*.ppl);;All files (*.*)" ));
	dialog.setViewMode( QFileDialog::List );
	if ( dialog.exec() ){
		QStringList fileNames = dialog.selectedFiles();
		currentFileNameIs( fileNames[ 0 ] );
		QFile file( currentFileName() );
		if( !file.open( QFile::ReadOnly | QFile::Text )){
			// to do issue an error
			return;
		}
		saveObjects();
		clearObjects();
		QXmlStreamReader xmlsr( &file );
		QXmlStreamReader::TokenType tokenType;
		tokenType = xmlsr.readNext();
		if( tokenType == QXmlStreamReader::StartDocument ){
			while( !xmlsr.atEnd() ){
				tokenType = xmlsr.readNext();
				if( tokenType == QXmlStreamReader::StartElement ){
					if( xmlsr.name() == "pipeline" ){
						readXmlObjects( xmlsr );
					}
				}
			}//while
		}
		if( xmlsr.error() ){
			restoreObjects();
			// to do clear and redraw
		}
		else{
			restoreLinks();
			restoreGraphs();
			createTree();
		}
	}

}

void EditorWindow::restoreLinks()
{
	foreach( Uniform * uniform, uniforms() ){
		uniform->restoreLinks( this );
	}//foreach
	foreach( Buffer * buffer, buffers() ){
		buffer->restoreLinks( this );
	}//foreach
	foreach( Stage * stage, stages() ){
		stage->restoreLinks( this );
	}//foreach
}

void EditorWindow::readXmlObjects( QXmlStreamReader & xmlsr )
{
	while( !xmlsr.atEnd() ){
		QXmlStreamReader::TokenType tokenType = xmlsr.readNext();
		std::string s = xmlsr.name().toString().toStdString();
		if( tokenType == QXmlStreamReader::EndElement ){
		}
		else if( tokenType == QXmlStreamReader::StartElement ){
			if( xmlsr.name() == "uniform" ){
				Uniform * node = new Uniform( mView, this );
				node->readXml( xmlsr );
				mScene->addItem( node );
				node->formatText();
				mUniforms.insert( node->name(), node );
			}
			else if( xmlsr.name() == "equation" ){
				Equation * node = new Equation( mView, this );
				node->readXml( xmlsr );
				mScene->addItem( node );
				node->formatText();
				mEquations.insert( node->name(), node );
			}
			else if( xmlsr.name() == "buffer" ){
				Buffer * node = new Buffer( mView, this );
				node->readXml( xmlsr );
				mScene->addItem( node );
				node->formatText();
				mBuffers.insert( node->name(), node );
			}
			else if( xmlsr.name() == "kernel" ){
				Kernel * node = new Kernel( mView, this );
				node->readXml( xmlsr );
				mScene->addItem( node );
				node->formatText();
				mKernels.insert( node->name(), node );
			}
			else if( xmlsr.name() == "stage" ){
				Stage * node = new Stage( mView, this );
				node->readXml( xmlsr );
				mScene->addItem( node );
				node->formatText();
				mStages.insert( node->name(), node );
			}
			else if( xmlsr.name() == "controlGraph" ){
				Graph * node = new Graph( mView, this );
				node->readXml( xmlsr );
				mControlGraphs.insert( node->name(), node );
			}
		}
	}
}

Graph * EditorWindow::findGraph( Node * node )
{
	if( node->graph() != NULL ){
		return node->graph();
	}
	foreach( Link * link, node->myLinks ){
		if( link->fromNode() != NULL && link->fromNode()->graph() != NULL ){
			return link->fromNode()->graph();
		}
		if( link->toNode() != NULL && link->toNode()->graph() != NULL ){
			return link->toNode()->graph();
		}
	}//foreach
	return NULL;
}


void EditorWindow::coalesceGraphs( Graph * fromGraph, Graph * toGraph )
{
	foreach( Edge edge, toGraph->edges() ){
		fromGraph->edges().append( edge );
	}//foreach
	toGraph->vertices().clear();
	toGraph->edges().clear();
	mControlGraphs.remove( toGraph->name() );
	delete toGraph;
}

QString EditorWindow::currentBaseFileName() const
{
	QString filePath = currentFileName();
	QStringList split = filePath.split( "/" );
	if( split.size() > 0 ){
		QString filename = split[ split.size() - 1 ];
		QStringList finalSplit = filename.split( "." );
		return finalSplit[ 0 ];
	}
	return "undefined";
}

void EditorWindow::buildProgram()
{
	char fileName[ 1024 ];
	strcpy( fileName, currentBaseFileName().toStdString().c_str() );
	strcat( fileName, ".pdl" );
	std::ofstream file;
	file.open( (const char *)fileName, std::ios::out );

	file << "Pipeline " << currentBaseFileName().toStdString() 
		<< "{ target=OpenCL; }{" << std::endl;

	foreach( Uniform * uniform, uniforms() ){
		uniform->build( file );
	}//foreach
	file << std::endl;
	foreach( Equation * equation, equations() ){
		equation->build( file );
	}//foreach
	file << std::endl;
	foreach( Buffer * buffer, buffers() ){
		buffer->build( file );
	}//foreach
	file << std::endl;
	foreach( Kernel * kernel, kernels() ){
		kernel->build( file );
	}//foreach
	file << std::endl;
	foreach( Stage * stage, stages() ){
		stage->build( file );
	}//foreach
	file << std::endl;
	foreach( Graph * graph, controlGraphs() ){
		graph->build( file );
	}//foreach
	file << "}" << std::endl;

	file.close();
}

